package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.OnRecyclerItemClickListener;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.Glide4Engine;
import com.kmproject.haifu.di.component.DaggerHousePushUpdateImgComponent;
import com.kmproject.haifu.mvp.contract.HousePushUpdateImgContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.resbean.ImgBean;
import com.kmproject.haifu.mvp.presenter.HousePushUpdateImgPresenter;
import com.kmproject.haifu.mvp.ui.adapter.AddImgAdapter;
import com.kmproject.haifu.mvp.ui.widget.Subject;
import com.kmproject.haifu.mvp.ui.widget.SwipeRecyclerView;
import com.library.flowlayout.SpaceItemDecoration;
//import com.swifty.dragsquareimage.DraggablePresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/28/2019 17:07
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HousePushUpdateImgActivity extends BaseActivity<HousePushUpdateImgPresenter> implements HousePushUpdateImgContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.activity_house_push_update_img_btn)
    TextView activityHousePushUpdateImgBtn;

    @BindView(R.id.recyclerView)
    SwipeRecyclerView mRecyclerView;
    @BindView(R.id.HousePushUpdateImg_recyclerView)
    RecyclerView HousePushUpdateImgRecyclerView;
    @BindView(R.id.add_img_top_item_img)
    ImageView addImgTopItemImg;
    @BindView(R.id.add_img_top_item_del)
    ImageView addImgTopItemDel;
    @BindView(R.id.linearLayout2)
    ConstraintLayout linearLayout2;
    //    @BindView(R.id.drag_square)
//    DraggableSquareView dragSquare;
//    private DraggablePresenter draggablePresent;
    RxPermissions mRxPermissions;

    private List<Subject> datas = new ArrayList<>();
    private ItemTouchHelper mItemTouchHelper;
    //    private MyAdapter myAdapter;
    private List<ImgBean> imgBeans = new ArrayList<>();//上传图片地址封装

    private AddImgAdapter addImgAdapter;
//    private ImageView imageViewHeadView;
    private int index;
   private boolean updateFirstImg=false;//是否是更改封面
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHousePushUpdateImgComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_house_push_update_img; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initView();
        mRxPermissions = new RxPermissions(this);
        if (getIntent().hasExtra("type") && getIntent().getStringExtra("type").equals("selectImg")&&!getIntent().hasExtra("imgs")) {
            //去选择图片
            mPresenter.requestPrisession(0);
            return;
        }
        List<ImgBean> temImgs=   (List<ImgBean>) getIntent().getSerializableExtra("imgs");
        datas.clear();
        for (ImgBean imgBean:temImgs)
        {
            datas.add(new Subject(imgBean.getImageUrl(),imgBean.getImageType()));
        }
        referView();

    }

    /**
     * 删除图片
     * @param delindex
     */
    public void showDelDialog(final int delindex)
    {
        new AlertView("", "确定删除？", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {

            @Override
            public void onItemClick(Object o, int position) {
                if (position == AlertView.CANCELPOSITION) {
                    //取消
                } else {
                    datas.remove(delindex+1);
                    referView();
                }
            }
        }).show();
    }

    @Override
    public void showLoading() {
          loadingDialog.show();
    }

    @Override
    public void hideLoading() {
         loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.activity_house_push_update_img_btn,R.id.add_img_top_item_del})
    public void onClick(View view ) {
        switch (view.getId())
        {
            case R.id.activity_house_push_update_img_btn:
                if (datas == null && !datas.isEmpty() || datas.size()<1) {
                    showMessage("至少选择一张图片");
                    return;
                }
                activityHousePushUpdateImgBtn.setEnabled(false);
                loadingDialog.show();
                mPresenter.updateHeadImg(0, datas.get(0));
                break;
            case R.id.add_img_top_item_del:
                if (datas.isEmpty())
                {
                    showMessage("请选择封面");
                    return;
                }
                datas.remove(0);
                if (datas.isEmpty())
                {
                    addImgTopItemDel.setVisibility(View.INVISIBLE);
                }
                referView();
                break;
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null ) {
            if (requestCode == 1005|| requestCode == AppConstant.REQUEST_CODE_CHOOSE)
            {
                List<Uri> temSelected=Matisse.obtainResult(data);
                if (temSelected!=null&&!temSelected.isEmpty())
                {
                    YsImg(temSelected);
                }
            }

        }else {
            if (requestCode==1005)
            {
                killMyself();
            }
        }

    }

    public void YsImg(final List<Uri> temmSelected) {

        if (temmSelected != null && !temmSelected.isEmpty()) {
            for (int i = 0; i < temmSelected.size(); i++) {
                index = i;
                AppUtil.getBitmapFromUri(this, temmSelected.get(i));
                String path = AppUtil.getFromMediaUri(this, getContentResolver(), temmSelected.get(i));
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    if (file != null && file.exists()) {
                        Luban.with(this)
                                .load(file)
                                .ignoreBy(100)
                                //                                .setTargetDir()
                                .filter(new CompressionPredicate() {
                                    @Override
                                    public boolean apply(String path) {
                                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                    }
                                })
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        if (updateFirstImg)
                                        {
                                            //如果是更改封面，移除第一张图
                                            datas.remove(0);
                                        }

                                        //上传图片
                                        if (datas.size() > 20) {
                                            showMessage("最多只能选择20张图片");
                                            return;
                                        }
                                       if (updateFirstImg)
                                       {
                                           datas.add(0,new Subject(file, file.getPath()));
                                       }else {
                                           datas.add(new Subject(file, file.getPath()));
                                       }
                                        updateFirstImg=false;
                                        if (index == temmSelected.size() - 1) {
                                            referView();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                    }

                                }).launch();

                    }
                }
            }
//            myAdapter.refershData(datas);
        }

    }

    /**
     * 刷新数据
     */
    public void referView()
    {
        if (datas.get(0).getServerPath()!=null&&!TextUtils.isEmpty(datas.get(0).getServerPath()))
        {
            Glide.with(this)
                    .load(datas.get(0).getServerPath())
                    .into(addImgTopItemImg);
        }else {
            Glide.with(this)
                    .load(datas.get(0).getFilepath())
                    .into(addImgTopItemImg);
        }

        List<Subject> temPath=new ArrayList<>();
        if (datas.size()>1)
        {
            for (int i=1;i<datas.size();i++)
            {
                temPath.add(datas.get(i));
            }
        }
        temPath.add(null);//最后一个
        addImgAdapter.setNewData(temPath);

    }
    @Override
    public RxPermissions getPermissions() {
        return mRxPermissions;
    }

    @Override
    public void requestPerimissionSuccess(int type) {
        //拍照界面
         Matisse.from(HousePushUpdateImgActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .captureStrategy(
//                new CaptureStrategy(true, "com.lxc.inspectionmanagement.fileprovider"))
                        new CaptureStrategy(true, "com.kmproject.haifu.fileprovider"))
                .maxSelectable(20)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(type==0?1005:AppConstant.REQUEST_CODE_CHOOSE);
    }

    @Override
    public void updateImgSuccess(int index, String sercerPath) {
        datas.get(index).setServerPath(sercerPath);
        imgBeans.add(new ImgBean(sercerPath, sercerPath.substring(sercerPath.lastIndexOf(".") + 1, sercerPath.length())));
        if (datas.size() - 1 > index) {
            mPresenter.updateHeadImg(index + 1, datas.get(index + 1));
        } else {
           runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   loadingDialog.dismiss();
                   //上传成功
                   showMessage("图片上传成功");
               }
           });
            Intent intent = new Intent();
            intent.putExtra("imgs", (Serializable) imgBeans);
            setResult(RESULT_OK, intent);
            activityHousePushUpdateImgBtn.setEnabled(true);
            killMyself();

        }
    }

    @Override
    public void updateImgFail(int index) {
        loadingDialog.dismiss();
        activityHousePushUpdateImgBtn.setEnabled(true);
        mPresenter.updateHeadImg(index, datas.get(index));
    }

    @Override
    public void updateImgFail() {
        loadingDialog.dismiss();
        activityHousePushUpdateImgBtn.setEnabled(true);
    }


    private void initView() {
        HousePushUpdateImgRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        addImgAdapter = new AddImgAdapter(null);
        HousePushUpdateImgRecyclerView.setAdapter(addImgAdapter);
        HousePushUpdateImgRecyclerView.addItemDecoration(new SpaceItemDecoration(dp2px(2)));
        addImgAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showDelDialog(position);
            }
        });
        addImgTopItemDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDelDialog(0);
            }
        });
        addImgTopItemImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateFirstImg=true;
                //拍照界面,更改封面
                Matisse.from(HousePushUpdateImgActivity.this)
                        .choose(MimeType.ofImage())
                        .countable(true)
                        .capture(true)
                        .captureStrategy(
//                new CaptureStrategy(true, "com.lxc.inspectionmanagement.fileprovider"))
                                new CaptureStrategy(true, "com.kmproject.haifu.fileprovider"))
                        .maxSelectable(1)
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new Glide4Engine())
                        .forResult(AppConstant.REQUEST_CODE_CHOOSE);
            }
        });


        mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                Toast.makeText(HousePushUpdateImgActivity.this, datas.get(vh.getLayoutPosition()).getTitle(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //判断被拖拽的是否是前两个，如果不是则执行拖拽
                if (vh.getLayoutPosition() != 0 && vh.getLayoutPosition() != 1) {
                    mItemTouchHelper.startDrag(vh);

                    //获取系统震动服务
//                    Vibrator vib = (Vibrator) getystemService(Service.VIBRATOR_SERVICE);//震动70毫秒
////                    vib.vibrate(70);

                }
            }
        });

        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            /**
             * 是否处理滑动事件 以及拖拽和滑动的方向 如果是列表类型的RecyclerView的只存在UP和DOWN，如果是网格类RecyclerView则还应该多有LEFT和RIGHT
             * @param recyclerView
             * @param viewHolder
             * @return
             */
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
//                    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(datas, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(datas, i, i - 1);
                    }
                }
//                myAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//                int position = viewHolder.getAdapterPosition();
//                myAdapter.notifyItemRemoved(position);
//                datas.remove(position);
            }

            /**
             * 重写拖拽可用
             * @return
             */
            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            /**
             * 长按选中Item的时候开始调用
             *
             * @param viewHolder
             * @param actionState
             */
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            /**
             * 手指松开的时候还原
             * @param recyclerView
             * @param viewHolder
             */
            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);
            }
        });

        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

        mRecyclerView.setRightClickListener(new SwipeRecyclerView.OnRightClickListener() {
            @Override
            public void onRightClick(int position, String id) {
                datas.remove(position);
//                myAdapter.notifyItemRemoved(position);
//                myAdapter.notifyDataSetChanged();
                Toast.makeText(HousePushUpdateImgActivity.this, " position = " + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

}
